#import "BMSOnlineSessionManager.h"
#import <UIKit/UIKit.h>
#import "BMSPrivate.h"
#define kBMSOnlineDurationKey @"bms.totalOnlineSeconds"

@interface BMSOnlineSessionManager ()
@property (nonatomic, assign) NSTimeInterval totalOnlineSeconds;
@property (nonatomic, assign) NSTimeInterval sessionStartTime;
@property (nonatomic, strong) NSTimer *tickTimer;
@property (nonatomic, assign) BOOL isTracking;
@end

@implementation BMSOnlineSessionManager

+ (instancetype)shared {
    static BMSOnlineSessionManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.totalOnlineSeconds = [[NSUserDefaults standardUserDefaults] doubleForKey:kBMSOnlineDurationKey];
        NSLog(@"[BMS Online TIME] Loaded totalOnlineSeconds: %.2f", self.totalOnlineSeconds);

//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground)
//                                                     name:UIApplicationDidEnterBackgroundNotification object:nil];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForeground)
//                                                     name:UIApplicationWillEnterForegroundNotification object:nil];
    }
    return self;
}

- (void)startTracking {
    if (self.isTracking) return;

    self.sessionStartTime = [[NSDate date] timeIntervalSince1970];
    self.isTracking = YES;

    NSLog(@"[BMS Online TIME] startTracking at %.0f", self.sessionStartTime);
    [self startTickTimer];
}

- (void)stopTracking {
    if (!self.isTracking) return;

    [self saveCurrentSessionDuration];
    [self stopTickTimer];
    self.isTracking = NO;

    NSLog(@"[BMS Online TIME] stopTracking");
}

- (void)appDidEnterBackground {
    NSLog(@"[BMS Online TIME] App did enter background");
    [self stopTracking];
}

- (void)appWillEnterForeground {
    NSLog(@"[BMS Online TIME] App will enter foreground");
    BOOL didRealName = [[NSUserDefaults standardUserDefaults]boolForKey:kBMSKeyRealnameAuth];
    if(didRealName != YES){
        [self startTracking];
    }
}

- (void)saveCurrentSessionDuration {
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval delta = now - self.sessionStartTime;
    if (delta > 0) {
        self.totalOnlineSeconds += delta;
        NSLog(@"[BMS Online TIME] Save +%.2fs → total = %.2fs", delta, self.totalOnlineSeconds);
        [self persistOnlineTime];
    }
}

- (void)persistOnlineTime {
    [[NSUserDefaults standardUserDefaults] setDouble:self.totalOnlineSeconds forKey:kBMSOnlineDurationKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)startTickTimer {
    if (self.tickTimer) return;

    self.tickTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(tickTimerFired) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.tickTimer forMode:NSRunLoopCommonModes];
    NSLog(@"[BMS Online TIME] Tick timer started.");
}

- (void)stopTickTimer {
    [self.tickTimer invalidate];
    self.tickTimer = nil;
    NSLog(@"[BMS Online TIME] Tick timer stopped.");
}

- (void)tickTimerFired {
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval currentSession = now - self.sessionStartTime;
    NSTimeInterval total = self.totalOnlineSeconds + currentSession;

    NSLog(@"[BMS Online TIME] Tick: current=%.2fs, total=%.2fs", currentSession, total);
    if (self.onTickCheck) {
        self.onTickCheck(total);
    }
}

- (NSTimeInterval)currentTotalOnlineSeconds {
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval session = (self.isTracking ? now - self.sessionStartTime : 0);
    return self.totalOnlineSeconds + session;
}

- (void)resetOnlineTime {
    NSLog(@"[BMS Online TIME] Reset all time");
    self.totalOnlineSeconds = 0;
    self.sessionStartTime = 0;
    self.isTracking = NO;
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kBMSOnlineDurationKey];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
